<?php

namespace app\common\service\user;

use app\admin\model\Config;
use app\admin\model\order\Order;
use app\admin\model\order\OrderGoodsInfo;
use app\admin\model\store\GoodsSku;
use app\admin\model\User;
use app\admin\model\user\UserPay;
use app\admin\model\user\UserRetailConfig;
use app\admin\model\user\UserRetailFlow;
use app\common\service\BaseService;
use think\facade\Cache;

class UserRetailService extends BaseService
{
    /**
     * Author:Zhongyuan Lu
     * 获取默认的分销比例
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getRetailProportion()
    {
        $redis = Cache::store('redis');
        $redis->select(1);
        $config = $redis->get('user_retail_config:default_proportion');
        $retailGoodsPrice = $redis->get('user_retail_config:retail_goods_price');

        //判断redis中是否有默认的分销比例（分销金额划分的比例）
        if (empty($config)) {
            $retailId = Config::where('field_name','default_retail_id')->value('value');
            $config = UserRetailConfig::field(['id','one_level_retail','two_level_retail','three_level_retail'])->find($retailId)->toArray();
            $redis->set('user_retail_config:default_proportion',json_encode($config));
        }else {
            $config = json_decode($config,true);
        }

        //判断redis中是否有商品参与分销总金额的比例
        if (empty($retailGoodsPrice)) {
            $retailGoodsPrice = Config::where('field_name','retail_goods_price')->value('value');
            $redis->set('user_retail_config:retail_goods_price',$retailGoodsPrice);
        }
        $config['retailGoodsPrice'] = intval($retailGoodsPrice);

        return $config;
    }

    /**
     * Author:Zhongyuan Lu
     * 生成用户分销流水
     * @param $uid
     * @param $order_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function createRetailFlow($uid,$order_id)
    {
        $config = self::getRetailProportion();

        $user = User::field(['one_level_distributor','two_level_distributor','three_level_distributor'])->find($uid)->toArray();
        $userRetailFlow = $user;
        $userRetailFlow['uid'] = $uid;
        $userRetailFlow['order_id'] = $order_id;
        $userRetailFlow['retail_id'] = intval(Config::where('field_name','default_retail_id')->value('value'));
        $userRetailFlow['one_level_price'] = $userRetailFlow['two_level_price'] = $userRetailFlow['three_level_price'] = 0;
        $where = [
            ['uid','=',$uid],
            ['order_id','=',$order_id],
        ];
        //获得用户下单记录
        $order = UserPay::where($where)->select();
        $order && $order = $order->toArray();

        foreach ($order as $k=>&$v) {
            //若此商品没有设置分销金额  则走系统默认配置
            if (empty($v['sku_retail_price'])) {
                //利润 == 商品成交价-商品成本价
                $profit = $v['sku_price'] - $v['sku_cost_price'];
                //商品的可分销金额 == 利润 * 默认比例 * 购买数量
                $v['sku_retail_price'] = $profit * $config['retailGoodsPrice'] / 100 * $v['sku_num'];
            }
            //三級分销金额计算公式 商品可分销金额 * 分销比例
            if (!empty($userRetailFlow['one_level_distributor'])) {
                $userRetailFlow['one_level_price'] += $v['sku_retail_price'] * $config['one_level_retail'] / 100;
            }else {
                break;
            }

            if (!empty($userRetailFlow['two_level_distributor'])) {
                $userRetailFlow['two_level_price'] += $v['sku_retail_price'] * $config['two_level_retail'] / 100;
            }

            if (!empty($userRetailFlow['three_level_distributor'])) {
                $userRetailFlow['three_level_price'] += $v['sku_retail_price'] * $config['three_level_retail'] / 100;
            }
        }
        unset($v);

        $bool = UserRetailFlow::create($userRetailFlow);
        if ($bool) {
            return self::success('添加成功');
        }
        return self::fail('添加失败');
    }
}